# import threading
#
# from PyQt5.QtCore import QThread, QSettings
# from pyaudio import PyAudio
# import wave
# import os
# import logging.config
# import traceback
# from util.Tools import Tools
#
# # settings = QSettings(Tools.resource_path("config\\config.ini"), QSettings.IniFormat)
# # settings.setIniCodec("UTF-8")
# logging.config.fileConfig(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "config\\logging.ini"))
# logging.getLogger("infoLogger")
#
# # TODO 语音播报
# class Speech(QThread):
#     def __init__(self,filename):
#         try:
#             super().__init__()
#             self.p = PyAudio()
#             self.CHUNK = 1024
#             self.FileName=filename
#         except Exception as f:
#             print(f)
#
#     def run(self):
#         # todo Tcp监听语音
#
#
#
#         try:
#             self.playSpeech()
#         except Exception as f:
#             print(f)
#
#     def playSpeech(self):
#         '''播报语音'''
#         try:
#             wf = wave.open(self.FileName, 'rb')
#             stream = self.p.open(format=self.p.get_format_from_width(wf.getsampwidth()),
#                                  channels=wf.getnchannels(), rate=wf.getframerate(),
#                                  output=True)  # 打开数据流--【获取音频格式信息】
#             # output=True   输出的意思
#             data = wf.readframes(self.CHUNK)  # 读取数据
#             while data != b'' and not (stream.is_stopped()):
#                 # stream.is_stopped()  流是否停止，如果停止返回True
#                 stream.write(data)  # 播放
#                 data = wf.readframes(self.CHUNK)
#             stream.stop_stream()
#             stream.close()
#         except Exception:
#             logging.error(traceback.format_exc())
#
#
#
#
#
#
# class Server_Collect(QThread):
#     tcp_action_signal = pyqtSignal(str)
#     def __init__(self):
#
#         super().__init__()
#         # self.HOST = setting.value("tcp_config/HTTP_IP_HOST")
#         self.POST = setting.value("SocketService/HTTP_IP_PORT")
#         self.add = ('', int(self.POST))
#         # 创建一个tcp套接字
#         self.listen_socket = socket(AF_INET, SOCK_STREAM)
#         # 允许立即使用上次绑定的port
#         self.listen_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
#         # 绑定
#         self.listen_socket.bind(self.add)
#         # 变为被动，并制定队列的长度
#         self.listen_socket.listen(128)
#
#     def run(self):
#         try:
#             while True:
#
#
#                 # 等待新客户端到来
#                 client_socket, client_address = self.listen_socket.accept()
#                 new_process = threading.Thread(target=self.handleRequest, args=(client_socket,))
#                 new_process.start()
#                 # 因为线程是共享同一个套接字，所以主线程不能关闭，否则子线程就不能再使用这个套接字了
#                 # client_socket.close()
#         except:
#             print("shibai")
#
#     def handleRequest(self, client_socket):
#         '''
#         :param client_socket:
#         :return:
#         '''
#         try:
#             recv_date = client_socket.recv(1024).decode("utf-8")
#             if len(recv_date) > 0:
#                 # todo 得到的实时音频流，解析分析音频流，播放音频
#                 # 得到的数据
#
#                 ret = FuncReduceHttpRequest(recv_date)
#                 self.tcp_action_signal.emit(str(ret))
#                 response_start_line = "HTTP/1.1 200 OK\r\n"
#                 response_headers = "Server: My server\r\n"
#                 response_body = "success"
#                 response = response_start_line + response_headers + "\r\n" + response_body
#                 client_socket.send(response.encode("utf-8"))
#             else:
#                 response_start_line = "HTTP/1.1 403 OK\r\n"
#                 response_headers = "Server: My server\r\n"
#                 response_body = "faled"
#                 response = response_start_line + response_headers + "\r\n" + response_body
#                 client_socket.send(response.encode("utf-8"))
#                 pass
#             client_socket.close()
#         except Exception as f:
#             print(f)
#
#
#
# def demo():
#     from socket import *
#
#     HOST = ''
#     PORT = 9000
#     BUFSIZ = 1024
#     ADDRESS = (HOST, PORT)
#
#     # 创建监听socket
#     tcpServerSocket = socket(AF_INET, SOCK_STREAM)
#
#     # 绑定IP地址和固定端口
#     tcpServerSocket.bind(ADDRESS)
#     print("服务器启动，监听端口{}...".format(ADDRESS[1]))
#
#     tcpServerSocket.listen(5)
#
#     try:
#         while True:
#             print('服务器正在运行，等待客户端连接...')
#
#             # client_socket是专为这个客户端服务的socket，client_address是包含客户端IP和端口的元组
#             client_socket, client_address = tcpServerSocket.accept()
#             print('客户端{}已连接！'.format(client_address))
#
#             try:
#                 while True:
#                     # 接收客户端发来的数据，阻塞，直到有数据到来
#                     # 事实上，除非当前客户端关闭后，才会跳转到外层的while循环，即一次只能服务一个客户
#                     # 如果客户端关闭了连接，data是空字符串
#                     data = client_socket.recv(2048)
#                     if data:
#                         print('接收到消息 {}({} bytes) 来自 {}'.format(data.decode('utf-8'), len(data), client_address))
#                         # 返回响应数据，将客户端发送来的数据原样返回
#                         client_socket.send(data)
#                         print('发送消息 {} 至 {}'.format(data.decode('utf-8'), client_address))
#                     else:
#                         print('客户端 {} 已断开！'.format(client_address))
#                         break
#             finally:
#                 # 关闭为这个客户端服务的socket
#                 client_socket.close()
#     finally:
#         # 关闭监听socket，不再响应其它客户端连接
#         tcpServerSocket.close()

# 说明：请先将 Config.py 中的配置项按需改成自己的值，然后再开始使用。
import RASRsdk
import os
import Config
# ----------------------------- 调用方法1 -----------------------------
# 音频文件路径
filepath = "../../test_wavs/8k.wav"
# 调用语音识别函数获得识别结果, 参数2标识是否打印中间结果到控制台
result = RASRsdk.sendVoice(filepath, True)
print("Final result: " + result)

# ---------------------------------------------------------------------
# 若需中途调整参数值，可直接修改，然后继续发请求即可。例如：
Config.config.ENGINE_MODEL_TYPE = '8k_0'

# ----------------------------- 调用方法2 -----------------------------
def requestExample():
    # 将音频文件分解成小的切片数据（即：切分成长度较小的多个字符串）发出。模拟不断发送数据接收回复，最终收完整句话的识别结果。
    filepath = "../../test_wavs/8k.wav"
    file_object = open(filepath, 'rb')
    file_object.seek(0, os.SEEK_END)
    datalen = file_object.tell()
    file_object.seek(0, os.SEEK_SET)

    # 发送请求时需要用户自行维护3个变量：voiceId：创建后保持不变； seq：递增； endFlag：前面为0，发送尾部分片的请求时设置为1
    voiceId = RASRsdk.randstr(16)
    seq = 0
    endFlag = 0
    while (datalen > 0):
        if (datalen < Config.config.CUT_LENGTH):
            endFlag = 1
            content = file_object.read(datalen)
        else:
            content = file_object.read(Config.config.CUT_LENGTH)
        res = RASRsdk.sendRequest(content, voiceId, seq, endFlag)
        print(res)  # 打印收到的结果到控制台。示例用途。
        seq = seq + 1
        datalen = datalen - Config.config.CUT_LENGTH
    file_object.close()

# 使用方法2
requestExample()
